package com.eslserver.servletapi.timer;

import java.io.IOException;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;

import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.esl.coordinator.command.Command;
import com.esl.coordinator.command.CommandInvoker;
import com.esl.coordinator.command.LoadImageDataTransferCommand;
import com.esl.coordinator.exception.STiTEQATMELIntegrationException;

public class CommandRetryJob implements Job {
	public static final Logger LOG = LoggerFactory
			.getLogger(CommandRetryJob.class);
	private static Queue<Command> commandRetryQueue = new ConcurrentLinkedQueue<Command>();

	@Override
	public void execute(JobExecutionContext arg0) throws JobExecutionException {

		Queue<Command> tmpQueue = new ConcurrentLinkedQueue<Command>();

		while (commandRetryQueue.size() > 0) {
			Command cmd = commandRetryQueue.remove();
			try {
				CommandInvoker.sendCommand(cmd);
				cmd.setRetryCount(cmd.getRetryCount() + 1);
			} catch (STiTEQATMELIntegrationException e) {
				LOG.error(e.getMessage(), e);
			} catch (IOException e) {
				LOG.error(e.getMessage(), e);
			}

			if (!cmd.isCommandSuccessful()) {
				tmpQueue.add(cmd);
			}
		}

		while (tmpQueue.size() > 0) {
			commandRetryQueue.add(tmpQueue.remove());
		}
	}

	public static void addCommand(Command cmd) {
		if (LoadImageDataTransferCommand.class.isAssignableFrom(cmd.getClass())) {
			commandRetryQueue.remove(cmd);
		}
		commandRetryQueue.add(cmd);
	}

	// TODO: remove needs to be called after ESL update
	public static void removeCommand(Command cmd) {
		if (LoadImageDataTransferCommand.class.isAssignableFrom(cmd.getClass())) {
			commandRetryQueue.remove(cmd);
		}
	}

}
